<?php

namespace Yearnfar\Bundle\CmsBundle\Controller;

use Doctrine\ORM\Tools\Pagination\Paginator;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Yearnfar\Bundle\CmsBundle\Entity\menu;

/**
 * @Route("/menu")
 * @Template()
 */
class MenuController extends BaseController
{
    /**
     * @Route("/")
     */
    public function indexAction()
    {
        $request = $this->get('request');

        $rows = max(1, $request->get('rows', 10));
        $page = max(1, $request->get('page', 1));

        $em   = $this->getDoctrine()->getManager();
        $menu = $em->getRepository('CmsBundle:menu')->findBy([], ['pid'=>'ASC', 'id'=>'ASC']);

        $callBack = function (&$result, $pid=0, $depth=-1) use (&$callBack, $menu) {
            $depth++;
            foreach ($menu as $om) {
                if ($om->getPid()==$pid) {
                    $om->name2 = str_repeat('——', $depth) . $om->getName();
                    $om->pName = isset($result[$pid]) ? $result[$pid]->getName() : '';

                    $result[$om->getId()]  = $om;
                    $callBack($result, $om->getId(), $depth);
                }
            }
        };

        $_menu = [];
        $callBack($_menu, 0, -1);
        $records = count($_menu);

        return [
            'menu'    => array_slice($_menu, ($page-1) * $rows, $rows),
            'records' => $records,
            'page'    => $page,
            'rows'    => $rows,
            'total'   => ceil($records/$rows)
        ];
    }

    /**
     * @Route("/edit")
     * @Template()
     */
    public function editAction()
    {
        $request = $this->get('request');
        $submit  = $request->get('submit');
        $mid     = $request->get('mid', 0);

        $em = $this->getDoctrine()->getManager();
        $current = $mid>0 ? $em->find('CmsBundle:menu', $mid) : new menu();

        $groups = $em->getRepository('CmsBundle:groups')->findAll();

        if ($submit) {
            $name  = $request->get('name',  '');
            $pid   = $request->get('pid', '');
            $route = $request->get('route', '');
            $class = $request->get('class', '');
            $_power= $request->get('power');
            $description = $request->get('description', '');
            //权限设置
            $power = 1;//开发者权限
            if (!empty($_power)) {
                foreach ($_power as $v) {
                    $power |= 1 << $v;
                }
            }

            $current
                ->setName($name)
                ->setPid($pid)
                ->setRoute($route)
                ->setClass($class)
                ->setPower($power)
                ->setDescription($description);

            $em->persist($current);
            $em->flush();

            if ($mid>0) {
                return $this->msgOut("修改菜单成功！", '/cms/menu/');
            }

            return $this->msgOut("添加菜单成功", '/cms/menu/');
        }

        $menu = $em->getRepository('CmsBundle:menu')->findBy([], ['pid'=>'ASC', 'id'=>'ASC']);

        $callBack = function (&$result, $pid=0, $depth=-1) use (&$callBack, $menu) {
            $depth++;
            foreach ($menu as $om) {
                if ($om->getPid()==$pid) {
                    $om->name2 = str_repeat('——', $depth) . $om->getName();

                    $result[]  = $om;
                    $callBack($result, $om->getId(), $depth);
                }
            }
        };

        $_menu = [];
        $callBack($_menu, 0, 0);

        return [
            'current'=> $current,
            'menu'   => $_menu,
            'groups' => $groups
        ];
    }

    /**
     * @Route("/delete")
     * @Template()
     */
    public function deleteAction()
    {
        return array(
                // ...
            );
    }

    /**
     * 显示所有子菜单
     * @param $menu
     * @param $pid
     * @param string $prefix
     * @return array
     */
    private function getSubMenu($menu, $pid, $prefix='——')
    {
        $_menu = [];
        foreach ($menu as $am) {
            $id = $am['id'];//当前菜单Id
            if ($id == $pid) {
                $am['aName'] = $am['name'];
                $_menu[$id]  = $am;
            } elseif ($am['pid']==$pid) {
                $_sub = $this->getSubMenu($menu, $id, $prefix);
                foreach ($_sub as $k => $v) {
                    $v['aName'] = $prefix . $v['aName'];//加前缀的菜单名
                    $_menu[$k]  = $v;
                }
            }
        }
        return $_menu;
    }

}
